import React, {Component} from "react";
import {ScrollView, View} from "react-native";
import chjStyle from "../../../CustomStyle";
import ModuleCommonHeader from "../../module/ModuleCommonHeader";
import CommonCheckItem from "./CommonCheckItem";
import {Actions} from "react-native-router-flux";

export default class CommonMultiListSelection extends Component {

    constructor(props) {
        super(props);

        this.state = {
            checkedArray: this.props.defaultValueArray ? this.props.defaultValueArray : []
        };
    }

    componentDidMount() {

    }

    render() {
        return (
            <View style={chjStyle.mainContainer}>
                <ModuleCommonHeader title={this.props.title} rightText='确定'
                                    clickedRight={this.onResult.bind(this)}/>
                <ScrollView
                    style={chjStyle.recordContainer}>
                    {this.props.optionArray.map((item, i) => this.renderExpenseItem(item, i))}
                </ScrollView>
            </View>
        );
    }

    onResult() {
        Actions.pop();
        this.props.onResultListener(this.state.checkedArray);
    }

    renderExpenseItem(item, i) {
        return <CommonCheckItem object={{name: item, checked: this.state.checkedArray.indexOf(item) !== -1}}
                                onValueChangedListener={ (value) => this.updateData(value, item, i)  }/>
    }

    updateData(value, item, i) {
        let index;
        if (value) {
            index = this.state.checkedArray.indexOf(item);
            if (index === -1) {
                this.state.checkedArray.push(item);
            }
        }
        else {
            index = this.state.checkedArray.indexOf(item);
            if (index !== -1) {
                this.state.checkedArray.splice(index, 1);
            }
        }
    }
}
